package iot

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"iot-base/common/dbobj"
)

type (
	HisData dbobj.HisData

	HisDataModel struct {
		db *gorm.DB
	}
)

func HisDataNew(db *gorm.DB) *HisDataModel {
	return &HisDataModel{db: db}
}

func (m *HisDataModel) Add(data *HisData) error {
	return m.db.Model(&HisData{}).Create(data).Error
}

func (m HisDataModel) QueryHisByTimeCount(stationId string, classType, startTime, endTime string) (int64, error) {
	var total int64
	err := m.db.Model(&HisData{}).
		Where("station_id = ?", stationId).
		Where("pick_time >= ?", startTime).
		Where("pick_time <= ?", endTime).
		Where("classify = ?", classType).
		Select("count(DISTINCT pick_time)").Find(&total).Error
	fmt.Println(total)
	return total, err
}

func (m HisDataModel) QueryHisByTime(stationId string, page int, size int, classType, startTime, endTime string) ([]HisData, error) {
	var result []HisData

	err := m.db.Model(&HisData{}).
		Where("pick_time in (?)", m.db.Select("DISTINCT pick_time").
			Where("station_id = ?", stationId).
			Where("pick_time >= ?", startTime).
			Where("pick_time <= ?", endTime).
			Where("classify = ?", classType).
			Limit(size).Offset((page-1)*size).
			Order("pick_time desc").Table("his_data")).Find(&result).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return []HisData{}, nil
	}
	if err != nil {
		return nil, err
	}
	return append([]HisData{}, result...), err
}
